package com.szqhyxj.youxiangju.biz.update;

import android.content.Context;
import android.util.Log;

import com.szqhyxj.youxiangju.BaseConsumer;
import com.szqhyxj.youxiangju.BasePresenterImpl;
import com.szqhyxj.youxiangju.biz.update.bean.UpdateInfo;
import com.szqhyxj.youxiangju.sys.util.PhoneManager;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class UpdatePresenter extends BasePresenterImpl implements UpdateContract.Presenter {

    private UpdateContract.View view;

    public UpdatePresenter(UpdateContract.View view) {
        this.view = view;
    }

    @Override
    public void checkUpdate(Context context) {
        final int localVersion = PhoneManager.getLocalVersion(context);
        startRequest(
                UpdateModel.checkUpdate(localVersion, null)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe((new BaseConsumer<UpdateInfo>() {
                            @Override
                            protected void error(String code, String msg) {
                            }

                            @Override
                            protected void successAccept(UpdateInfo updateInfo) {
                                if (localVersion < updateInfo.getVersionNumber()) {
                                    view.showUpdate(updateInfo);
//                                    Intent intent = new Intent(App.app, DownLoadService.class);
//                                    intent.putExtra("downloadurl",updateInfo.getDownloadLinks());
//                                    App.app.startService(intent);
                                }
                            }
                        }))
        );
    }

    private static final String TAG = UpdatePresenter.class.getSimpleName();

    @Override
    public void downloadAPK(File file, String url) {
        System.out.println(url);
        DownloadUtil.get().download1(url, file, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.i(TAG, "onDownloadSuccess: ");
                view.showDownCompleted(file.getAbsolutePath());
            }

            @Override
            public void onDownloading(int progress) {
                Log.i(TAG, "onDownloading: " + progress);
                view.showDownProgress(progress);
            }

            @Override
            public void onDownloadFailed() {
                Log.i(TAG, "onDownloadFailed: ");
                view.showDownloadFail();
            }
        });
    }
}